package com.bungarus;

import com.bungarus.client.busi.ClientHandler;
import com.bungarus.codec.protobuf.MessageProtobuf;
import com.bungarus.model.MessageType;
import com.bungarus.model.Session;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by tang on 2018/11/11.
 */
public class AccessTestClient {
    public static void main(String[] args) throws Exception {
        new AccessTestClient().connect("www.bungarus.com", 9080);
    }

    private void connect(String host, int port) throws Exception {
        Bootstrap client = new Bootstrap();
        client.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                        socketChannel.pipeline().addLast(new ProtobufDecoder(MessageProtobuf.Message.getDefaultInstance()));
                        socketChannel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                        socketChannel.pipeline().addLast(new ProtobufEncoder());
                        socketChannel.pipeline().addLast(new ClientHandler());
                    }
                });
        Channel channel = client.connect(host, port).sync().channel();
        while (true){
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String line = reader.readLine();

            /**
             * Test for login and IM message
             * type "login" in command line to login and get session id, and type other string to send IM message
             * asume that the current user data is {"accountName":"username"},{"accountName":"username","password":"password1","tenantId":"1000","id":100}
             * asume the current user send message to himself, so you will receive message sent by yourself
             */
            MessageProtobuf.Message message;
            if(line.equalsIgnoreCase("login")) {
                MessageProtobuf.Header header = MessageProtobuf.Header.newBuilder()
                        .setId("10000")
                        .setFrom("100")
                        .setTo("100")
                        .setLang("lang")
                        .setGaction(0)
                        .setApp("Apo")
                        .setDev("Device")
                        .setSessionId("")
                        .setTenantID(1000)
                        .setPriority(0)
                        .setType(MessageType.AUTH)
                        .setCredential(MessageProtobuf.Credential
                                .newBuilder()
                                .setUsername("username")
                                .setPwd("password1")
                                .build())
                        .addExtensions(MessageProtobuf.Extension
                                .newBuilder()
                                .setKey("client")
                                .setValue("value")
                                .build())
                        .build();
                MessageProtobuf.Body body = MessageProtobuf.Body.newBuilder()
                        .setContent("ctnt:java.lang.String:good morning! Content from cmd line -> " + line)
                        .build();
                message = MessageProtobuf.Message.newBuilder()
                        .setBody(body)
                        .setHeader(header)
                        .build();
            } else {
                /* try to get session from SesstionContainer, not work yet
                Session session = Access.getSessionContainer().findSessionByChannelId(channel.id());
                if(null == session){
                    System.out.println("------- session is null ");
                    continue;
                }
                */
                MessageProtobuf.Header header = MessageProtobuf.Header.newBuilder()
                        .setId("10000")
                        .setFrom("100")
                        .setTo("100")
                        .setLang("lang")
                        .setGaction(0)
                        .setApp("Apo")
                        .setDev("Device")
                        .setTenantID(1000)
                        .setSessionId(ClientHandler.sessionID) // use a static sessionId of ClientHandler temporarily
                        .setPriority(0)
                        .setType(MessageType.IM)
                        .build();
                MessageProtobuf.Body body = MessageProtobuf.Body.newBuilder()
                        .setContent("ctnt:java.lang.String:good morning! Content from cmd line -> " + line)
                        .build();
                message = MessageProtobuf.Message.newBuilder()
                        .setBody(body)
                        .setHeader(header)
                        .build();
            }

            channel.writeAndFlush(message).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(channelFuture.isSuccess()){
                        System.out.println("---------------------- client sent successfully!");
                    }
                }
            });
        }
    }

}
